<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="仓库编号" prop="configName">
        <el-input
          v-model="queryParams.warehouseId"
          placeholder="请输入仓库编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品编号" prop="configKey">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入商品编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="configKey">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="procRequest"
          >发送采购申请</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="batch_handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Refresh"
          @click="handleRefreshCache"
          >刷新缓存</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="configList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column
        label="仓库编号"
        align="center"
        prop="warehouseId"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="仓库名称"
        align="center"
        prop="warehouseName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="商品编号" align="center" prop="productId" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <el-table-column label="商品类别" align="center" prop="productCategory" />
      <el-table-column label="商品品牌" align="center" prop="productBrand" />
      <el-table-column label="库存数量" align="center" prop="quantity">
        <template #default="scope">
          <span :class="{ 'red-text': scope.row.quantity < 10 }">
            {{ scope.row.quantity }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="150"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)">
            修改
          </el-button>
          <el-button type="text" icon="Delete" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="configRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库编号" prop="warehouseId">
          <el-input v-model="form.warehouseId" placeholder="请输入仓库编号" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="商品编号" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入商品编号" />
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品类别" prop="productCategory">
          <el-input
            v-model="form.productCategory"
            placeholder="请输入商品类别"
          />
        </el-form-item>
        <el-form-item label="商品品牌" prop="productBrand">
          <el-input v-model="form.productBrand" placeholder="请输入商品品牌" />
        </el-form-item>
        <el-form-item label="商品数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入商品数量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 发送采购申请的弹窗 -->
    <el-dialog
      :title="Request_title"
      v-model="Request_open"
      width="500px"
      append-to-body
    >
      <el-form ref="configRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申请备注" prop="stoNote">
          <el-input v-model="GoodsRequest.stoNote" placeholder="备注" />
        </el-form-item>
        <el-form-item label="需要数量" prop="purchaseQuantity">
          <el-input
            v-model="GoodsRequest.purchaseQuantity"
            placeholder="请输入需要采购的数量"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="apply_purchase">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Config">
import {
  addConfig,
  addOrderDetail,
  gerMaxStoProId,
} from "@/api/procurement/proclist";
import {
  delConfig,
  getConfig,
  listConfig,
  updateConfig,
} from "@/api/reserve/warehouse";
import { ref } from "vue";

const { proxy } = getCurrentInstance();
// const { sys_yes_no } = proxy.useDict("sys_yes_no");

const configList = ref([]);
const open = ref(false);
const Request_open = ref(false); //用于控制采购申请弹窗
const loading = ref(true);
const showSearch = ref(true);
const Id = ref([]); //序号id唯一标识数组
const ids = ref([]); //选择的仓库编号的数组
const idpI = ref([]); //选择的商品编号的数组
const idpN = ref([]); //选择的商品名字的数组
const idpT = ref([]); //选择的商品的类别的数组
const idpB = ref([]); //选择的商品的品牌的数组
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const Request_title = ref(""); //采购申请弹窗的标题
const dateRange = ref([]);

//定义查询对象
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    warehouseId: undefined,
    productId: undefined,
    productName: undefined,
  },
  rules: {
    configName: [
      { required: true, message: "参数名称不能为空", trigger: "blur" },
    ],
    configKey: [
      { required: true, message: "参数键名不能为空", trigger: "blur" },
    ],
    configValue: [
      { required: true, message: "参数键值不能为空", trigger: "blur" },
    ],
  },
  condition: {
    page: 1,
    count: 10,
    maxPage: 0,
    total: 0,
    index: 0,
    search: {
      warehouseId: undefined,
      productId: undefined,
      productName: undefined,
    },
  },
  GoodsRequest: {
    stoProId: undefined,
    stoNote: undefined,
    productId: undefined,
    productName: undefined,
    productType: undefined,
    brand: undefined,
    purchaseQuantity: undefined,
  },
});

const { queryParams, form, rules, condition, GoodsRequest } = toRefs(data);

/** 查询参数列表 */
function getList() {
  loading.value = true;
  condition.value.page = queryParams.value.pageNum;
  condition.value.count = queryParams.value.pageSize;
  listConfig(condition.value).then((response) => {
    configList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  Request_open.value = false; // 关闭弹窗
  reset();
}
/** 表单重置 */
function reset() {}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  condition.value.search.warehouseId = queryParams.value.warehouseId;
  condition.value.search.productId = queryParams.value.productId;
  condition.value.search.productName = queryParams.value.productName;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.warehouseId = undefined;
  queryParams.value.productId = undefined;
  queryParams.value.productName = undefined;
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  Id.value = selection.map((item) => item.id);
  ids.value = selection.map((item) => item.warehouseId);
  idpI.value = selection.map((item) => item.productId);
  idpN.value = selection.map((item) => item.productName);
  idpT.value = selection.map((item) => item.productCategory);
  idpB.value = selection.map((item) => item.productBrand);
  single.value = !selection.length;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加参数";
  form.value.configId = undefined;
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const configId = row.id || ids.value;
  getConfig(configId).then((response) => {
    form.value = response.data;
    open.value = true;
    form.value.configId = configId;
    title.value = "修改参数";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["configRef"].validate((valid) => {
    if (valid) {
      if (form.value.configId !== undefined) {
        updateConfig(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addConfig(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const configIds = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除参数编号为"' + configIds + '"的数据项？')
    .then(function () {
      return delConfig(configIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/config/export",
    {
      ...queryParams.value,
    },
    `config_${new Date().getTime()}.xlsx`
  );
}
/** 刷新缓存按钮操作 */
function handleRefreshCache() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    warehouseId: undefined,
    productId: undefined,
    productName: undefined,
  };
  getList();
}
/** 批量删除的操作 */
function batch_handleDelete() {
  proxy.$modal
    .confirm("是否确认删除这些的数据？")
    .then(function () {
      const deletePromises = Id.value.map((id) => delConfig(id));
      return Promise.all(deletePromises);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch((error) => {
      proxy.$modal.msgError(`删除失败: ${error.message}`);
    });
}
/**发送采购申请的操作 */
function procRequest() {
  for (let Id of ids.value) {
    if (Id != ids.value[0]) {
      proxy.$modal.msgError("请选择同一个仓库");
      return;
    }
  }
  Request_open.value = true;
  Request_title.value = "发送采购申请";
}
/**提交采购申请的操作 */
async function apply_purchase() {
  try {
    // 添加配置
    await addConfig(GoodsRequest.value);

    // 获取最大 stoProId
    const { data: stoProId } = await gerMaxStoProId();
    GoodsRequest.stoProId = stoProId;

    // 删除之前表中的商品编号
    // await delOrderDetail(idpI.value[0]);

    // 使用 Promise.all 处理循环中的异步操作
    const orderDetails = idpI.value.map((productId, index) => ({
      stoProId: GoodsRequest.stoProId,
      productId: productId,
      productName: idpN.value[index],
      productType: idpT.value[index],
      brand: idpB.value[index],
      purchaseQuantity: GoodsRequest.value.purchaseQuantity,
    }));

    await Promise.all(orderDetails.map((detail) => addOrderDetail(detail)));

    // 成功提示
    proxy.$modal.msgSuccess("申请发送成功");
    Request_open.value = false; // 关闭弹窗
  } catch (error) {
    // 错误处理
    proxy.$modal.msgError(`申请发送失败: ${error.message}`);
  }
}
getList();
</script>

<style scoped>
.red-text {
  color: red;
}
</style>
